/**
 * @author 吴宇亮
 * @describe 文件上传模块的js
 * @date 2019-10-23
 */

//预览文件
function _previewImage(src){
    //防止特殊字符
    // let prefix = src.substring(0, src.lastIndexOf(fileSeprator) + 1)
    //     ,suffix = src.substring(src.lastIndexOf(fileSeprator) + 1);
    // let url = prefix + encodeURIComponent(suffix);

    let body = $("body"),
        layerIframe = $("iframe", window.parent.document);

    //宽高比例尺
    let widthScale = layerIframe ? layerIframe[0].offsetParent.clientWidth * 0.8 : body.width() * 0.8,
        heigthScale = layerIframe ? layerIframe[0].offsetParent.clientHeight * 0.8 : body.height() * 0.8;
    let oImg = new Image();
    // oImg.src = url;
    oImg.src = src;
    oImg.onload = function () {
        //获取原图的长宽比
        let _width, _height;
        if(heigthScale < widthScale){ //如果屏幕的高度 小于 屏幕的宽度，则图片的最大长度按屏幕的最小宽度来
            _height = heigthScale;
            _width = oImg.naturalWidth * _height / oImg.naturalHeight;
        }else{
            _width = widthScale;
            _height = oImg.naturalHeight * _width / oImg.naturalWidth;
        }

        let img = `<img src="${oImg.src}" style="width:${_width}px; height:${_height}px;">`;
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            area: [_width, _height],
            skin: 'layui-layer-nobg', //没有背景色
            shadeClose: true,
            content: img
        });
    }
}

function _deleteFilesWithComfirm(imgDiv){
    imgDiv.find('.layui-upload-delete').on('click', function(){
        let lid = $(this).attr("lid")
            ,fileName = $(this).attr("fileName");
        if(!lid || !fileName){
            throw new Error("imgDiv中必须含有自定义属性【lid】、【fileName】");
        }

        layer.open({
            content: `是否确定删除 \${fileName}？`,
            btn: ['确定', '取消'],
            yes: function(layerIndex) {
                $.post("/Upload.do?method=deleteFiles", {"sysFileLids": lid}, function(response){
                    if(response.code != RESPONSE_SUCCESS) {
                        layer.msg(response.msg,{icon:2});
                        return;
                    }
                    imgDiv.remove();
                    layer.close(layerIndex);
                }, "json");
            }
        });
    });
}

/**
 * 用来批量删除：新增页面，用户没有保存主表却上传了附件，然后正常关闭了页面所遗留的垃圾文件
 * @param sysFileLids 文件sys_file的主键，用","分隔
 */
function _deleteFiles(sysFileLids){
    let result = true;
    $.ajax({
        type: "POST",
        url: "/Upload.do?method=deleteFiles",
        data: {sysFileLids: sysFileLids},
        dataType: "json",
        async: false,
        success: function(data){
            if(data.code != RESPONSE_SUCCESS){
                result = false;
                layer.msg(data.msg,{icon:2})
                return;
            }
            return true;
        }
    });
    return result;
}



